/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.util;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A handler for rejected tasks that will have the caller block until
 * space is available.
 */
public class BlockPolicy implements RejectedExecutionHandler {
  private static Logger logger = LoggerFactory.getLogger(BlockPolicy.class);
  /**
   * Creates a <tt>BlockPolicy</tt>.
   */
  public BlockPolicy() {}
  /*
   * Puts the Runnable to the blocking queue, effectively blocking
   * the delegating thread until space is available.
   * @param r the runnable task requested to be executed
   * @param e the executor attempting to execute this task
   */
  public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
    try {
      e.getQueue().put(r);
    }
    catch (InterruptedException e1) {
      logger.error("task discarded, thread was interrupted while waiting for space to schedule: {}", r);
    }
  }
}
